package zybMySQL

import (
	"fmt"
	_ "github.com/go-sql-driver/mysql"
	"github.com/jmoiron/sqlx"
	"os"
	"zyb/zybPublic"
)

type ZybMySQL struct {
	userName string
	password string
	ip       string
	port     uint32
	db       string
	charset  string
	fcLog    func(l zybPublic.LogLevel,strLog string)
	strconn  string
	conn     *sqlx.DB
}

func NewMySQLObject(userName, password, ip, db, charset string,
	port uint32, f func(l zybPublic.LogLevel, strLog string))  *ZybMySQL{

	strConn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=%s", userName, password, ip, port, db, charset)

	return &ZybMySQL{
		userName: userName,
		password: password,
		ip:       ip,
		port:     port,
		db:       db,
		charset:  charset,
		fcLog:    f,
		strconn: strConn,
	}
}

func (r *ZybMySQL)checkError(strlabel string, err error)  {
	if err != nil {
		fmt.Println(strlabel, "fail :", err)
		r.fcLog(zybPublic.LogErrorLevel, strlabel + " " + "fail :" + err.Error())
		os.Exit(2)
	}
}

func (r *ZybMySQL)Init() bool {
	var err error
	r.conn, err = sqlx.Open("mysql", r.strconn)
	r.checkError("init mysql", err)
	return err == nil
}

func (r *ZybMySQL)Conn() *sqlx.DB {
	return  r.conn
}